// 新增复制模板
import CommonModal from "@/components/CommonModal";
import CommonLoading from "@/components/CommonLoading";
import SelectShop from "@/components/SelectShop";
import { useEffect, useState } from "react";
import { Form, Popover, message, Input, InputNumber } from "antd";
import Iconfont from "@/components/IconFont";
import styles from "./index.module.less";
import { queryLabelStoreIdList } from "../../service";

const layout = {
	labelCol: {
		span: 8
	},
	wrapperCol: {
		span: 14
	}
};

//类型
const textMap = {
	1: "新增",
	2: "编辑",
	3: "复制"
};

//不同尺寸新增对应的模板id
const sizeTemplateIdMap = {
	"60*40": 1634963420,
	"50*80": 1634963421,
	"76*130": 1634963422,
	"210*148": 1634963423,
	"210*297": 1634963424
};

/** 新增复制模板 */
function AddCopyTemplate(props) {
	const { type, recordData, commonParams, handleCancel, handleOk } = props;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	const [selectShops, setSelectShops] = useState([]); //选择的店铺
	const [shopVisible, setShopVisible] = useState(false); // 店铺弹窗
	const [storeIds, setStoreIds] = useState([]); //已存在的店铺id

	const [form] = Form.useForm();

	useEffect(() => {
		setOpen(true);
		form.resetFields();
		getLabelStoreIdList();
	}, []);

	useEffect(() => {
		if (["2"].includes(type)) {
			setSelectShops(recordData.ecStoreList);
		}
	}, [type, recordData]);

	useEffect(() => {
		if (selectShops.length) {
			form.setFieldsValue({
				ecStoreIds: selectShops.map(item => (item.systemStoreName ? item.systemStoreName : item.storeName)).join(",")
			});
		} else {
			form.setFieldsValue({ ecStoreIds: "" });
		}
	}, [selectShops]);

	//已存在的店铺
	const getLabelStoreIdList = async () => {
		setLoading(true);
		const { data = [], success } = await queryLabelStoreIdList({
			labelType: recordData.labelType
		});
		if (success) {
			setStoreIds(data);
		}
		setLoading(false);
	};

	const onOk = () => {
		form
			.validateFields()
			.then(val => {
				if (type != 2) {
					if (recordData.labelType == 4) {
						//门市打印新增
						handleOk({ ...val, ecStoreIds: selectShops.map(item => item.id) });
					} else {
						//新增
						handleCreateTemplateId({ ...val, ecStoreIds: selectShops.map(item => item.id).join(",") });
					}
				}
				setIsOk(true);
				setOpen(false);
			})
			.catch(info => {
				console.log("Validate Failed:", info);
			});
	};

	//新增模板
	const handleCreateTemplateId = params => {
		KMTEMPLATE.copyTemplate({
			...commonParams,
			id:
				type == 3
					? Number(recordData.kmTemplateCode)
					: sizeTemplateIdMap[`${recordData.sizeWidth}*${recordData.sizeHeight}`] || 1634963420,
			callback: res => {
				if (res) {
					params.templateId = res;
					handleOk(params);
				}
			}
		});
	};

	//问号以及对应文案展示
	const iconTextRender = text => {
		return (
			<Popover content={<div style={{ width: "300px" }}>{text}</div>}>
				<span>
					<Iconfont type="iconwenhao1" />
				</span>
			</Popover>
		);
	};

	//清除店铺/标签弹窗
	const handleClear = e => {
		const val = e.target.value;
		if (val == "") {
			setSelectShops([]);
		}
	};

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			handleCancel();
		} else {
			handleCancel();
		}
	};

	//店铺组件
	const SelectShopProps = {
		storeIds,
		selectShops: selectShops.map(item => item.id),
		handleCancel() {
			setShopVisible(false);
		},
		handleOk(arr) {
			setShopVisible(false);
			setSelectShops(arr);
		}
	};

	return (
		<CommonModal
			title={`${textMap[type]}模板`}
			afterClose={afterClose}
			open={open}
			width="450px"
			onOk={onOk}
			onCancel={onCancel}
			okText={"继续编辑"}
            minHeight="100px"
		>
			<Form
				form={form}
				// className="new-search-form-style"
				onFinish={() => {}}
				name="express-warning-search-form"
				initialValues={{ templateName: ["2", "3"].includes(type) ? recordData.templateName : "" }}
				{...layout}
			>
				<Form.Item
					label="模板名称"
					name="templateName"
					rules={[
						{ required: true, message: "请输入模版名称" },
						{ max: 50, message: "最多输入50个字符！" }
					]}
				>
					<Input placeholder="请输入模板名称" />
				</Form.Item>
				<Form.Item label="请选择店铺">
					{[8, 9, 10].includes(recordData.labelType) ? (
						"-"
					) : (
						<div style={{ display: "flex" }}>
							<Form.Item noStyle label="请选择店铺" name="ecStoreIds">
								<Input
									allowClear
									onChange={e => handleClear(e)}
									onClick={() => setShopVisible(true)}
									placeholder="请选择店铺"
									suffix={<Iconfont onClick={() => setShopVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
								/>
							</Form.Item>
							{iconTextRender("为空时打印取对应模块的默认模板；选择后打印时对应店铺取该模板")}
						</div>
					)}
				</Form.Item>
				{/* <Form.Item label={<span className={styles.labelReqire}>模板宽高(毫米)</span>} style={{ display: "inline-flex" }}>
					<div style={{ display: "flex" }}>
						<Form.Item name="sizeWidth" rules={[{ required: true, message: "请输入宽度" }]}>
							<InputNumber min={1} />
						</Form.Item>
						<span style={{ marginRight: "6px", marginLeft: "6px" }}>*</span>
						<Form.Item rules={[{ required: true, message: "请输入高度" }]} name="sizeHeight">
							<InputNumber min={1} />
						</Form.Item>
					</div>
				</Form.Item> */}
			</Form>
			{shopVisible && <SelectShop {...SelectShopProps} />}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default AddCopyTemplate;
